//
//  ImageViewController.m
//  LLSimpleCameraExample
//
//  Created by Ömer Faruk Gül on 15/11/14.
//  Copyright (c) 2014 Ömer Faruk Gül. All rights reserved.
//

#import "ImageViewController.h"
#import "ViewUtils.h"
#import "UIImage+Crop.h"

@interface ImageViewController ()
@property (strong, nonatomic) UIImage *image;
@property (strong, nonatomic) UIImageView *imageView;
@property (strong, nonatomic) UIButton *cancelBtn,*uploadBtn;
@property (strong, nonatomic) UIButton *cancelButton;
@end

@implementation ImageViewController

- (instancetype)initWithImage:(UIImage *)image {
    self = [super initWithNibName:nil bundle:nil];
    if(self) {
        _image = image;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.imageView.backgroundColor = [UIColor blackColor];
    
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, screenRect.size.width, screenRect.size.height)];
    self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    self.imageView.backgroundColor = [UIColor clearColor];
    self.imageView.image = self.image;
    [self.view addSubview:self.imageView];
    
    self.cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.cancelBtn.frame = CGRectMake(0, 0, 70.0f, 70.0f);
    self.cancelBtn.clipsToBounds = YES;
    [self.cancelBtn setTitle:@"重拍" forState:UIControlStateNormal];
    self.cancelBtn.layer.cornerRadius = self.cancelBtn.width / 2.0f;
    self.cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.cancelBtn setTitleColor:[UIColor colorWithHexString:@"0x9b9b9b"] forState:UIControlStateNormal];
    self.cancelBtn.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
    self.cancelBtn.layer.rasterizationScale = [UIScreen mainScreen].scale;
    self.cancelBtn.layer.shouldRasterize = YES;
    [self.cancelBtn addTarget:self action:@selector(cancelButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.cancelBtn];
    
    
    self.uploadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.uploadBtn.frame = CGRectMake(0, 0, 70.0f, 70.0f);
    self.uploadBtn.clipsToBounds = YES;
    [self.uploadBtn setTitle:@"上传" forState:UIControlStateNormal];
    self.uploadBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.uploadBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.uploadBtn.layer.cornerRadius = self.uploadBtn.width / 2.0f;
    self.uploadBtn.backgroundColor = [UIColor colorWithHexString:kMainColor] ;
    self.uploadBtn.layer.rasterizationScale = [UIScreen mainScreen].scale;
    self.uploadBtn.layer.shouldRasterize = YES;
    [self.uploadBtn addTarget:self action:@selector(uploadButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.uploadBtn];
    
}


- (void)cancelButtonPressed {
    [self dismissViewControllerAnimated:NO completion:nil];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = [UIColor clearColor];
    }
}

- (void)uploadButtonPressed{
    
    NSDictionary *param;
    if(!self.studentUid){
        param = @{
                  @"exercise_uid":self.exerciseUid
                  };
    }else{
        param = @{
                  @"exercise_uid":self.exerciseUid,
                  @"student_uid":self.studentUid
                  };
    }
    
    [self.view showProcess];
    
    __weak typeof(self) weakSelf = self;
    
    [[XZBNetAPIClient sharedJsonClient] requestJsonDataWithPath:@"v1/pool/image/access" withParams:param withMethodType:Get andBlock:^(id responseData, NSError *error){
        
        if(!error){
            NSDictionary *data = [responseData objectForKey:@"data"];
            NSDictionary *uploadParams = @{
                                           @"key":[NSString stringWithFormat:@"%@%@-origin.jpg",[data objectForKey:@"dir"],[NSObject getUUID]],
                                           @"policy":[data objectForKey:@"policy"],
                                           @"OSSAccessKeyId":[data objectForKey:@"accessid"],
                                           @"signature":[data objectForKey:@"signature"]
                                           };
            
            NSLog(@"%@",uploadParams);
            [[XZBNetAPIClient sharedJsonClient] uploadImage:weakSelf.image path:[data objectForKey:@"host"] params:uploadParams successBlock:^(AFHTTPRequestOperation *operation , id responseObject){
                NSLog(@"%@",responseObject);
                NSDictionary *syanParmas;
                if(self.studentUid){
                    syanParmas = @{
                                   @"uid":[NSObject getUUID],
                                   @"exercise_uid":weakSelf.exerciseUid,
                                   @"student_uid":weakSelf.studentUid
                                   };

                }else{
                    syanParmas = @{
                                   @"uid":[NSObject getUUID],
                                   @"exercise_uid":weakSelf.exerciseUid
                                   };

                }
                [[XZBNetAPIClient sharedJsonClient] requestJsonDataWithPath:@"v1/pool/image/access" withParams:syanParmas withMethodType:Post andBlock:^(id responseData, NSError *error){
                    if(!error){
                        [weakSelf.view showSuccess:@"上传成功"];
                        [weakSelf dismissViewControllerAnimated:YES completion:nil];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"UploadSuccess" object:nil];
                       
                    }
                }];
                
                
            } failureBlock:^(AFHTTPRequestOperation *operation , NSError *error){
                [weakSelf.view hideProcess];
            } progerssBlock:^(CGFloat progressValue){
                [weakSelf.view showProcessWithStatus:@"图片上传中..." process:progressValue];
            }];
        }
    }];
    
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    self.imageView.frame = self.view.contentBounds;
    self.cancelBtn.center = self.view.contentCenter;
    self.cancelBtn.bottom = self.view.height - 15.0f;
    self.cancelBtn.left = (self.view.width/4) - 35.0f;
    
    
    self.uploadBtn.center = self.view.contentCenter;
    self.uploadBtn.bottom = self.view.height - 15.0f;
    self.uploadBtn.right = (self.view.width*3/4) + 35.0f;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
